import {
  login,
  logout,
  getInfo,
  checkExpirationTime,
  verificationSecurityQuestionList,
} from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { Notification, MessageBox } from "element-ui";
import { getConfigKey } from "@/api/system/config";

const user = {
  state: {
    token: getToken(),
    name: "",
    password: "",
    userId: "",
    loginId: "",
    avatar: "",
    roles: [],
    permissions: [],
    dialogFormVisibleExpirationDayNum: false, // 密码时效性小于5的时候显示
    dialogFirstLoginVisible: sessionStorage.getItem("firstLogin") || false, // 是否第一次登录
    city_name: undefined,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_FIRSTLOGIN: (state, dialogFirstLoginVisible) => {
      dialogFirstLoginVisible
        ? sessionStorage.setItem("firstLogin", dialogFirstLoginVisible)
        : sessionStorage.removeItem("firstLogin");
      state.dialogFirstLoginVisible = dialogFirstLoginVisible;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_LOGINID: (state, loginId) => {
      state.loginId = loginId;
    },
    SET_USERID: (state, userId) => {
      state.userId = userId;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_PASSWORD: (state, password) => {
      state.password = password;
    },
    SET_dialogFormVisibleExpirationDayNum: (
      state,
      dialogFormVisibleExpirationDayNum
    ) => {
      state.dialogFormVisibleExpirationDayNum =
        dialogFormVisibleExpirationDayNum;
    },
    SET_CITY_NAME: (state, city_name) => {
      state.city_name = city_name;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            console.log("res: ", res);
            if (res.code == 203) {
              resolve(res);
              return;
            }
            if (res.code == 200) {
              setToken(res.token);
              commit("SET_TOKEN", res.token);
              commit("SET_FIRSTLOGIN", res.firstLogin);

              resolve(res);
            } else {
              reject(error);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    TwoLogin({ commit }, ticketForm) {
      return new Promise((resolve, reject) => {
        verificationSecurityQuestionList(ticketForm)
          .then((res) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    SET_dialogFormVisibleExpirationDayNum({ commit }, bool) {
      commit("SET_dialogFormVisibleExpirationDayNum", bool);
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            if (!res?.user) return;

            checkExpirationTime().then((res) => {
              if (res.code == 200 && res.expirationDayNum <= 5) {
                commit("SET_dialogFormVisibleExpirationDayNum", true);
                Notification.info(
                  `您的密码将于${res.expirationDayNum}天后过期，请及时修改密码`
                );
              }
            });
            const user = res.user;
            const avatar =
              user.avatar == null
                ? require("@/assets/images/profile.jpg")
                : process.env.VUE_APP_BASE_API + user.avatar;
            let aaa = res.user.roleList.map((item) => {
              return item.roleKey;
            });
            if (aaa && aaa.length > 0) {
              // 验证返回的roles是否是一个非空数组
              // commit('SET_ROLES', res.roles)   // 后台返回的res.roles 是假的
              commit("SET_ROLES", aaa);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            commit("SET_PERMISSIONS", res.permissions);

            commit("SET_LOGINID", user.loginId);
            commit("SET_PASSWORD", user.password);
            commit("SET_NAME", user.name);
            commit("SET_USERID", user.userId);
            commit("SET_AVATAR", avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    GetCityName({ commit, state }, city_name) {
      commit("SET_CITY_NAME", city_name);
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    // FedLogOut({ commit }) {
    //   return new Promise(resolve => {
    //     commit('SET_TOKEN', '')
    //     removeToken()
    //     resolve()
    //   })
    // }
  },
};

export default user;
